<template>
  <NpDialog :visible.sync="dialogPvVisible" width="608px" class="container">
    <template>
      <div class="title">新增/编辑资源包</div>
      <div class="con">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleFormRef" label-width="86px">
          <el-form-item label="包类型" prop="packetType">
            <el-radio-group v-model="ruleForm.packetType">
              <el-radio-button v-for="(item, index) in packetTypeOptions" :key="index" :label="item.id">
                <i class="el-icon-success"></i>
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="解答文档" prop="packageUrl">
            <div class="upload_warp1" v-show="!ruleForm.packageUrl">
              <el-upload ref="upload_ref1" action="#" multiple :limit="1" :auto-upload="false" :on-change="handleChange"
                :file-list="fileList">
                <el-button type="info"><i class="el-icon-upload el-icon--right"></i> 上传文档</el-button>
              </el-upload>
              <div class="tips">
                <i class="el-icon-info"></i>上传APK资源包文件
              </div>
            </div>
            <div class="operate_warp" v-show="ruleForm.packageUrl">
              <div class="name">{{ ruleForm.packageUrl }}</div>
              <div class="row1">
                <el-upload ref="upload_ref2" action="#" multiple :limit="1" :auto-upload="false" :file-list="fileList"
                  :on-change="handleChange">
                  <i class="el-icon-upload"></i>
                </el-upload>
                <i class="el-icon-delete" @click="handleDeleteFile"></i>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="版本号" prop="targetVersion">
            <el-input v-model="ruleForm.targetVersion" placeholder="请输入问题标题"></el-input>
          </el-form-item>
          <el-form-item label="发行说明" prop="releaseNotes">
            <el-input v-model="ruleForm.releaseNotes" placeholder="请输入问题标题"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="fotter">
        <el-button type="info" plain class="btn1" @click="uploadCancelClick"
          :disabled="file_upload_loading">取消</el-button>
        <el-button type="warning" @click="uploadImportClick('ruleFormRef')" :disabled="file_upload_loading"
          :loading="submitLoading">确定</el-button>
      </div>
    </template>
  </NpDialog>
</template>
<script>
import NpDialog from "@/components/np/Dialog/index.vue"
import { uploadFile, downloadFile } from "@/api/public"
import {
  addUPgrade,
  updateUPgrade,
} from '@/api/ota-upgrade-management/list'

export default {
  components: {
    NpDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    packetTypeOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    infoRow: {
      type: Object,
      default: () => {
        return null
      }
    }
  },
  data() {
    let com_blur__rule = [{ required: true, message: '此字段为必填。', trigger: 'blur' }],
      com_change__rule = [{ required: true, message: '此字段为必填。', trigger: 'change' }];
    return {
      dialogPvVisible: false,

      submitLoading: false, // 表单 loading
      file_upload_loading: false, // 文件上传 loading

      fileList: [],
      ruleForm: {
        packetType: 1,

        packageUrl: '',
        upgradeName: '',

        targetVersion: '',
        releaseNotes: '',
      },
      rules: {
        packetType: com_blur__rule,
        packageUrl: com_change__rule,

        targetVersion: com_change__rule,
        releaseNotes: com_change__rule,
      },
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogPvVisible = newVal;
        if (newVal) {
          if (this.infoRow) {
            this.editInfo()
            return
          }
        }
        if (!newVal) {
          this.resetFieldsFrom()
        }
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.infoRow
    },
    isAdd() {
      return !this.infoRow
    },
  },
  created() {
  },
  methods: {
    editInfo() {
      let arr1 = Object.keys(this.ruleForm);
      arr1.forEach(el => {
        this.ruleForm[el] = this.infoRow[el] || this.ruleForm[el]
      })
    },
    resetFieldsFrom() {
      this.fileList = []
      Object.keys(this.ruleForm).forEach(el => {
        if (el === 'packetType') {
          this.ruleForm[el] = 1
          return
        }
        this.ruleForm[el] = ''
      })
    },
    handleChange(file, fileList) {
      console.log(file);

      if (!this.isExcel(file)) {
        this.$message.error('仅支持上传.apk、.zip、.tar后缀文件')
        this.fileList = [];
        return
      }
      this.fileList = [file];

      let params = new FormData();
      params.append("type", 4);
      params.append("file", file.raw);

      this.file_upload_loading = true
      uploadFile(params).then(res => {
        this.fileList = [];
        if (res.code === 200) {
          this.ruleForm.upgradeName = file.name
          this.ruleForm.packageUrl = res.data
        } else {
          this.$message.error('上传失败。')
        }
        // 因为文件可能很大，手动提前释放一下资源
        file = null
        this.file_upload_loading = false
      }).catch(err => {
        this.fileList = [];
        file = null
        this.file_upload_loading = false
        this.$message.error('系统错误，服务失败。')
      })
    },
    handleDeleteFile() {
      this.fileList = [];
      this.ruleForm.packageUrl = ''
      this.ruleForm.upgradeName = ''
    },
    uploadCancelClick() {
      if (this.file_upload_loading || this.submitLoading) {
        return
      }
      this.dialogPvVisible = false
      this.submitLoading = false
      this.fileList = [];
      this.$refs['ruleFormRef'].resetFields()
      this.$emit("update:visible", this.dialogPvVisible)
    },
    uploadImportClick(formName) {
      if (this.file_upload_loading || this.submitLoading) {
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = this.ruleForm,
            fun = addUPgrade;

          if (this.isEdit) {
            fun = updateUPgrade;
            params.id = this.infoRow.id || ''
          }

          this.submitLoading = true
          fun(params).then(res => {
            let data = this.isEdit ? 'edit' : 'add',
              obj = {
                add: '新增',
                edit: '编辑',
              };
            if (res.code === 200) {
              this.$message.success(`${obj[data]}成功!`)
              setTimeout(() => {
                this.submitLoading = false;
                this.uploadCancelClick()
                this.$emit("editAddSuccessChange", data)
              }, 1000)
              return
            } if (res.code === 1020) {
              this.$message.error(`${obj[data]}失败。数据填写重复`)
            } else {
              this.$message.error(res.message || `${obj[data]}失败。`)
            }
            this.submitLoading = false;
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
            this.submitLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    isExcel(file) {
      return /\.(apk|zip|tar)$/.test(file.name)
    },
  }
}
</script>
<style lang="scss" scoped>
.title {
  padding-bottom: 32px;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  color: #15181D;
}

.fotter {
  padding-top: 12px;
  display: flex;
  justify-content: right;
  align-items: center;

  .btn1 {
    margin-right: 12px;
  }
}

.upload_warp1 {
  display: flex;

  .tips {
    i {
      padding: 0 6px 0 16px;
    }
  }
}

.operate_warp {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .name {
    font-size: 14px;
    line-height: 18px;
    color: #C27B55;
  }

  .row1 {
    display: flex;
    justify-content: right;
    align-items: center;
  }

  .el-icon-upload {
    margin: 0 20px 0 40px;
  }
}

.container {
  ::v-deep {
    @media (max-width: 1280px) {
      .np-el-d-body {
        padding: 24px 40px 40px 24px;
        min-height: 264px;
      }
    }
  }
}

::v-deep {
  .el-upload-list {
    display: none;
  }

  .con {
    .el-form-item__label {
      font-size: 14px;
      font-weight: normal;
      color: #8B8B8B;
    }
  }
}
</style>